package com.example.statistics.ex

import android.content.Context
import android.graphics.PorterDuff
import android.text.Editable
import android.text.TextWatcher
import android.text.method.ReplacementTransformationMethod
import android.view.View
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.ColorRes
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.statistics.R
import com.jhj.slimadapter.holder.ViewInjector
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.anko.dip
import org.jetbrains.anko.sdk27.coroutines.onLongClick
import org.jetbrains.anko.toast
import java.math.BigDecimal


fun View.color(@ColorRes color: Int) = context.getResColor(color)


fun ImageView.colorFilter(color: Int) =
    this.setColorFilter(color, PorterDuff.Mode.SRC_IN)

//===========ImageView===========
fun ImageView.glide(imgPath: Any, options: RequestOptions) {
    Glide.with(context).asBitmap().load(imgPath).apply(options).into(this)
}

fun ImageView.glide(path: Any) {
    glide(path, RequestOptions().placeholder(R.drawable.ic_pig))
}

fun ImageView.glideRound(path: Any, radius: Int = dip(6)) {
    glide(
        if (path == "") R.drawable.ic_pig else path, RequestOptions()
            .placeholder(R.drawable.ic_pig)
            .apply(RequestOptions().transforms(CenterCrop(), RoundedCorners(radius)))
    )
}

fun ImageView.glideCircle(path: Any) {

    glide(
        if (path == "") R.drawable.ic_pig else path,
        RequestOptions().placeholder(R.drawable.ic_pig).transform(CircleCrop())
    )
}

fun ImageView.glideNoCache(path: Any) {
    glide(
        if (path == "") R.drawable.ic_pig else path,
        RequestOptions().placeholder(R.drawable.ic_pig).diskCacheStrategy(
            DiskCacheStrategy.NONE
        )
    )
}

fun View.openKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager;
    imm.showSoftInput(this, InputMethodManager.RESULT_SHOWN)
    imm.toggleSoftInput(
        InputMethodManager.SHOW_FORCED,
        InputMethodManager.HIDE_IMPLICIT_ONLY
    );
}

fun View.onSingleLongClicked(vararg str: String, body: (String) -> Unit) {
    this.onLongClick {
        context.singleDialog(*str) { str ->
            body.invoke(str)
        }
    }
}

fun <T : IDialogModel> View.onSingleLongClicked(vararg t: T, body: (T) -> Unit) {
    this.onLongClick {
        context.singleDialog(*t) { str ->
            body.invoke(str)
        }
    }
}

fun <T : IDialogModel> View.onActionTLongClicked(vararg pairs: Pair<T, (T) -> Unit>) {
    this.onLongClick {
        context.actionTDialog(*pairs)
    }
}

fun View.onActionLongClicked(vararg pairs: Pair<String, (String) -> Unit>) {
    this.onLongClick {
        context.actionDialog(*pairs)
    }
}


var TextView?.contentText: String?
    get() {
        return if (this == null) {
            ""
        } else if (this.text.toString().isNumber()) {
            this.text.toString().numberFormat
        } else {
            this.text.toString()
        }
    }
    set(value) {
        this?.text = if (value == null) {
            ""
        } else if (value.isNumber()) {
            value.numberFormat
        } else {
            value.toString()
        }
    }


/**
 *  如果textview的内容是数值，则返回
 */
val TextView.textStringToNumber: Double
    get() = if (this.contentText.isNumber()) {
        this.contentText.toString().toDouble()
    } else {
        0.0
    }

fun View.closeKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager;
    imm.hideSoftInputFromWindow(windowToken, 0)
}


fun ViewInjector.glide(id: Int, path: Any): ViewInjector {
    val imageView = getView<ImageView>(id)
    imageView.glide(path)
    return this
}

fun ViewInjector.onSingleLongClicked(vararg str: String, body: (String) -> Unit): ViewInjector {
    this.with {
        it.onSingleLongClicked(*str) { s ->
            body.invoke(s)
        }
    }
    return this
}

fun <T : IDialogModel> ViewInjector.onSingleLongClicked(vararg str: T, body: (T) -> Unit): ViewInjector {
    this.with {
        it.onSingleLongClicked(*str) { s ->
            body.invoke(s)
        }
    }
    return this
}


fun <T : IDialogModel> ViewInjector.onActionTLongClicked(vararg pairs: Pair<T, (T) -> Unit>): ViewInjector {
    this.with {
        it.onActionTLongClicked(*pairs)
    }
    return this
}

fun ViewInjector.onActionLongClicked(vararg pairs: Pair<String, (String) -> Unit>): ViewInjector {
    this.longClicked {
        it.context.actionDialog(*pairs)
        false
    }
    return this
}


fun ViewInjector.glideRound(id: Int, path: Any): ViewInjector {
    val imageView = getView<ImageView>(id)
    imageView.glideRound(path)
    return this
}

fun ViewInjector.glideCircle(id: Int, path: Any): ViewInjector {
    val imageView = getView<ImageView>(id)
    imageView.glideCircle(path)
    return this
}

fun View.rotate(action: () -> Unit) {
    val loadAnimation = AnimationUtils.loadAnimation(context, R.anim.anim_rotate);
    val lin = LinearInterpolator()
    loadAnimation.interpolator = lin
    if (loadAnimation != null) {
        this.clearAnimation();
        this.startAnimation(loadAnimation);
    }
    GlobalScope.launch(Dispatchers.Main) {
        delay(400)
        action()
    }
}


fun TextView.afterTextChangedListener(body: (Editable?, TextView) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            body(s, this@afterTextChangedListener)
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }
    })
}

/**
 * 小写转大写
 */
fun EditText.toUpperCase() {
    transformationMethod = object : ReplacementTransformationMethod() {
        override fun getOriginal(): CharArray {
            return charArrayOf(
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
            );
        }

        override fun getReplacement(): CharArray {
            return charArrayOf(
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
            )
        }
    }
}

fun TextView.maxLimit(max: Float?) {
    this.afterTextChangedListener { editable, textView ->


    }
}


/**
 * 录入最大值限制
 */
fun Editable?.maxLimit(context: Context, max: Float?): Float {
    var number = this.toString()
    if (number.isNumber()) {
        if (number.toFloat() > (max ?: 0f)) {
            number = number.substring(0, number.length - 1)
            this?.replace(0, this.length, number.trim { it <= ' ' })
            context.toast("最大值不能大于${max}")
            if (number.isBlank())
                return 0f
            return number.toFloat()
        }
        return number.toFloat()
    }
    return 0f
}

